var selectedRow= '';
$("#dataTable").on("click-row.bs.table",function(e,row,ele){
    $("#dataTable .success").removeClass("success");
    $(ele).addClass("success");
    selectedRow = row;
});

$(function () {
    newCheck.initByName('error_text');
    newCheck.initByName('del_text');
    newCheck.initByName('lesson_common');
    initTextSearch("#pIsvName"
        ,basePath + 'health/searchIsvList?t='+ (new Date()).getTime()+'&isvName='
        ,['isvPid','isvName'],{'isvPid':"服务商pid",'isvName':'服务商名称'}
        ,'isvPid','isvName'
        ,true,
        selectPisvValue,
        noSelectPisvValue,
        false
    );
    initTextSearch("#pDocName"
        ,basePath + 'health/searchDocList?t='+ (new Date()).getTime()+'&docName='
        ,['docCode','docName'],{'docCode':"专家编码",'docName':'专家姓名'}
        ,'docName','docName'
        ,true,
        selectPdocValue,
        noSelectPdocValue,
        false
    );

    window.actionEvents = {
        'click .infoView': function(e, value, row, index) {
            //编辑操作
            selectedRow = row;
            openEnumPage();
        },
    }

    laydate.render({
        elem: '#gmtCreate'
        ,type: 'datetime'
        ,range: true //或 range: '~' 来自定义分割字符
        // ,value: dateFtt("yyyy-MM-dd hh:mm:ss", preDate) + ' - ' + dateFtt("yyyy-MM-dd hh:mm:ss", curDate)
        //js赋值重置失效，改为就是怕、页面赋值
        ,isInitValue: true //是否允许填充初始值，默认为 true
    });
});

function beforePublish() {
    if(selectedRow == ''){
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    if(selectedRow.dataStatus == 'pending_check'){
        toastr.error("待审核数据无法提交发布");
        return;
    }
    if(selectedRow.dataStatus == 'check_pass'){
        toastr.error("已审核数据无需提交发布");
        return;
    }
    showLoading();
    $.ajax({
        type: 'post',
        url: basePath + 'health/beforePublish',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify({
            contentCode:selectedRow.contentCode,
            docCode : selectedRow .docCode
        }),
        success : function (data) {
            if(data.result){
                publish();
            }else{
                toastr.error(data.message);
                hideLoading();
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
            hideLoading();
        }
    });
}

function publish(){
    var str = '确认提交发布吗？';
    swalToastr('提交发布', str, 'warning', doCommitContent, '确认提交');
    hideLoading();
}

function doCommitContent(){
    $.ajax({
        type: 'post',
        url: basePath + 'health/updateStatus',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify({
            id: selectedRow.id,
            contentCode: selectedRow.contentCode,
        }),
        success: function (data) {
            hideLoading();
            if (data.result) {
                //toastr.success(data.message);
                window.location.href = basePath + 'health/healthContentPage?t=' + new Date().getTime();
            } else {
                toastr.error(data.message);
            }
        },
        error: function (request) {
            hideLoading();
            toastr.error(common_system_error);
        }
    });
}

function add(){
    $("#pContentType").attr("disabled",false);
    $("#pContentType").val("");
    $("#bizCode").attr("disabled",false);
    $("#bizCode").val("");
    doWinRefresh();
    $('#addContent').modal(true);
    $('#typeDiv').hide();
}

function edit() {
    var tableOptions = $('#dataTable').bootstrapTable('getOptions', null);
    if(selectedRow == ''){
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    if(selectedRow.dataStatus == 'pending_check'){
        toastr.error("这是待审核数据不能编辑");
        return;
    }
    doWinRefresh();
    var pContentType;
    var lessonCommon;
    var bizCode;
    var id;
    var contentCode;
    if(selectedRow.contentType != 'lesson_series'){
        lessonCommon = selectedRow.contentType;
        pContentType = 'lesson_common';
    }else{
        pContentType = selectedRow.contentType;
        lessonCommon = selectedRow.contentType;
    }
    id = selectedRow.id;
    bizCode = selectedRow.bizCode;
    contentCode = selectedRow.contentCode;

    if(selectedRow.contentType == 'qa'){
        pContentType = selectedRow.contentType;
        lessonCommon = selectedRow.contentType;
    }

    window.location.href = basePath + 'health/updateEditPage?&contentType=' + pContentType + '&bizCode=' + bizCode +'&lessonCommon=' + lessonCommon +'&id='+id+'&contentCode='+contentCode+ '' +
        '&editType=edit&'+$('#searchForm').serialize()+'&t=' + new Date().getTime()+ '&pageNo=' + tableOptions.pageNumber + '&pageSize=' + tableOptions.pageSize;
    }

function changeContent(value){
    if(value == 'lesson_common'){
        $("#typeDiv").show();
    }
    if(value == 'lesson_series'){
        $("#typeDiv").hide();
    }
    if(value == 'qa'){
        $("#typeDiv").hide();
    }

}

function dele(){
    if(selectedRow == null || selectedRow == ''){
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    $("input[name=del_text]").removeAttrs('checked');
    $("#del_textarea").val("");
    if(selectedRow.dataStatus == 'pending_check'){
        toastr.error("这是待审核数据不能删除");
        return;
    }
    if(selectedRow.status == 'publish'){
        toastr.error("这是已发布数据，请先撤销再删除");
        return;
    }
    $("#delContentWin").modal(true);
}

function dodelContent() {
    var result = new Array();
    $("input[name=del_text]:checked").each(function (index,value) {
        result.push($(value).val());
    });
    if(result.length==0 && $("#del_textarea").val() == ''){
        toastr.error("请选择删除原因");
        return;
    }
    result.push($("#del_textarea").val());
    var postData = {};
    postData.id = selectedRow.id;
    postData.isvPid = selectedRow.isvPid;
    postData.refCode = selectedRow.refCode;
    postData.bizCode = selectedRow.bizCode;
    postData.contentCode = selectedRow.contentCode;
    postData.status = selectedRow.status;
    postData.dataStatus = 'delete';
    postData.revokeRemark = result.join(",");
    $.ajax({
        type: 'post',
        url: basePath + 'health/delContent',
        dataType: 'json',
        contentType: "application/json",
        beforeSend:function () {
            showLoading()
        },
        complete:function(){
            hideLoading();
        },
        data: JSON.stringify(postData),
        success : function (data) {
            if(data.result){
                toastr.success(data.message);
                doRefresh();
                $("#delContentWin").modal('hide');
            }else{
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function unPublishContent() {
    if(selectedRow == ''){
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }

    if(selectedRow.status == 'unpublished'){
        toastr.error("这是未发布数据无需撤销");
        return;
    }

    if(selectedRow.dataStatus == 'pending_check'){
        toastr.error("这是待审核数据不能撤销");
        return;
    }

    $("input[name=error_text]").removeAttrs('checked');
    $("#error_textarea").val("");
    $("#unPublishLessonWin").modal(true);
}


function doUnPublishContent() {
    var result = new Array();
    $("input[name=error_text]:checked").each(function (index,value) {
        result.push($(value).val());
    });
    if(result.length==0 && $("#error_textarea").val() == ''){
        toastr.error("请选择撤销原因");
        return;
    }
    result.push($("#error_textarea").val());
    var postData = {};
    postData.id = selectedRow.id;
    postData.contentCode = selectedRow.contentCode;
    postData.contentType = selectedRow.contentType;
    postData.isvPid = selectedRow.isvPid;
    postData.status = selectedRow.status;
    postData.revokeRemark = result.join(",");
    $.ajax({
        type: 'post',
        url: basePath + 'health/unPublishContent',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        beforeSend:function () {
            showLoading()
        },
        complete:function(){
            hideLoading();
        },
        success : function (data) {
            if(data.result){
                toastr.success(data.message);
                doRefresh();
                $("#unPublishLessonWin").modal("hide");
            }else{
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}


$('#scanQrCodePage').on('hidden.bs.modal', function () {
    // 执行一些动作...
    $('#scanCode').val('');
    $('#_validNum').val('');
});

function doImport(){
    $("#excelData").val('');
    $("#_fileName").html('');
    $('#_importTip').html('');
    $('#importResultLabel').html('');
    $('#_errorTipDiv').addClass('div-hidden');
    $("#excelNameShow").html('');
    $("#importPage").modal('show');

}

function downTemplate() {
    $('#_dataForm').attr("action", basePath + "health/getDialogExcelTemplate");
    $('#_dataForm').submit();
}

function fileChangeEvent(obj) {
    var id = $(obj).attr('id');
    var f = document.getElementById(id).files;
    if (!f) {
        return true;
    }
    var name = f[0].name;
    $('#excelNameShow').html(name);
}


function doImportQaExcel() {
    showLoading();
    $.ajaxFileUpload({
        type: 'post',
        url: basePath + 'health/excelImportDialogData',
        dataType: 'json',
        secureuri : false,
        fileElementId : ["excelData"],
        contentType : "application/json; charset=UTF-8",
        success : function (data) {
            hideLoading();
            if(data && data.result){
                //操作成功
                if(data.content) {
                    if (data.content.successNum == 0) {
                        toastr.error('没有可导入数据');
                        showImportMessage(data.content);
                    } else {
                        toastr.success('批量导入成功');
                        showImportMessage(data.content);
                    }

                }
            }else if(data&&!data.result){
                toastr.error(data.message);
            }else{
                toastr.error('操作失败');
            }
        },
        error: function (request) {
            hideLoading();
            delayToastr('系统错误');
            doRefresh();
        }
    });
}

function showImportMessage(data) {
    if (!data) return;
    $("#importResultLabel").html(data.importTip);
    if(data.failNum != 0){
        $('#errorTable').bootstrapTable('load', {
            data : data.errorData
        });$('#_errorTipDiv').removeClass('div-hidden');

    }
    $('#_ImportExcelDiv').removeClass('modal-body-height-new');
}


function download() {
    if (selectedRow == null) {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    $('#searchForm').attr("action", basePath + "health/exportContentExcel");
    $('#searchForm').submit();
}
function doWinRefresh() {
    $('#WinTable').bootstrapTable('refresh', {
        url: basePath + 'health/pageFindContentData?t=' + new Date().getTime(),
    });
}

function selectPisvValue(data){
    if (!data || !data.isvPid) {
        return;
    }
    $('#PisvPid').val(data.isvPid);
}
function noSelectPisvValue(){
    $('#PisvPid').val('');
}

function selectPdocValue(data){
    if (!data || !data.docCode) {
        return;
    }
    $('#pDocCode').val(data.docCode);
}
function noSelectPdocValue(){
    $('#pDocCode').val('');
}

function doRefresh() {
    selectedRow = '';
    var gmtStart = '';
    var gmtEnd = '';
    var timeInterval = $("#gmtCreate").val();
    var pDocName = $("#pDocName").val();
    var pIsvName = $("#pIsvName").val();
    if(timeInterval){
        var dates = timeInterval.split(' - ');
        if(dates && dates.length >1){
            gmtStart = dates[0];
            gmtEnd = dates[1];
        }
    }
    $('#dataTable').bootstrapTable('refresh', {
        url: basePath + 'health/pageFindContentData?t=' + new Date().getTime(),
        query: {
            createStartTimeStr : gmtStart,
            createEndTimeStr : gmtEnd,
            docName : pDocName,
            isvName : pIsvName
        }
    });
}

function doSaveType(){
    var tableOptions = $('#dataTable').bootstrapTable('getOptions', null);
    var pContentType = $("#pContentType").val();
    var bizCode = $("#bizCode").val();
    var lessonCommon = $('input[name="lesson_common"]:checked').val();

     if(pContentType == null || pContentType == ''){
         toastr.error('内容类型不能为空');
         return;
     }
     if(bizCode == null || bizCode == ''){
         toastr.error('服务项不能为空');
         return;
    }
    if(pContentType == 'lesson_common' && (lessonCommon == null || lessonCommon == '')){
        toastr.error("类别不能为空");
        return;
    }

    window.location.href = basePath + 'health/updateEditPage?contentType=' + pContentType + '&bizCode=' + bizCode +'&lessonCommon=' + lessonCommon +
       '&editType=add&'+$('#searchForm').serialize()+'&t=' + new Date().getTime()+ '&pageNo=' + tableOptions.pageNumber + '&pageSize=' + tableOptions.pageSize;
}


function showList() {
    if(selectedRow == ''){
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    var pContentType;
    var lessonCommon;
    var bizCode;
    var id;
    var contentCode;
    if(selectedRow.contentType == 'lesson_series'){
        pContentType = selectedRow.contentType;
        lessonCommon = selectedRow.contentType;
    }else if(selectedRow.contentType == 'qa'){
        pContentType = selectedRow.contentType;
        lessonCommon = selectedRow.contentType;
    }else{
        lessonCommon = selectedRow.contentType;
        pContentType = 'lesson_common';
    }
    id = selectedRow.id;
    bizCode = selectedRow.bizCode;
    contentCode = selectedRow.contentCode;
    docCode = selectedRow.docCode;
    $.ajax({
        type: 'post',
        url: basePath + 'health/openListPage?&contentType=' + pContentType + '&bizCode=' + bizCode +'&lessonCommon=' + lessonCommon +'&id='+id+'&contentCode='+contentCode+ '&docCode='+ docCode +'&t=' + new Date().getTime(),
        dataType: 'json',
        contentType : "application/json; charset=UTF-8",
        success : function (data) {
            if(data.result){
                $("#qrcode").html("");
                var content = data.content;
                initHealthQrCode(content.qrUrl);
                $("#_validNum").html(content.validNum);
                $("#scanQrCodePage").modal('show');
            }else{
                toastr.error(data.message);
            }
        }, error: function (request) {
            toastr.error(common_system_error);
        }
    });
}


function initHealthQrCode(url) {
    $('#qrcode').qrcode({
        height: 240,
        width: 240,
        text: url
    });
}

//**************************************初始化表单**********************************************************  //

function formatStatus(value, row, index) {
    if (!value || value == '') {
        return '';
    }
    return publishStatus[value];
}

function formatContentType(value, row, index) {
    if (!value || value == '') {
        return '';
    }
    return contentType[value];
}

function formatDataStatus(value, row, index) {
    if (!value || value == '') {
        return '';
    }
    return dataStatus[value];
}

function formatType(value, row, index){
    if (!value || value == '') {
        return '';
    }
    return YesOrNo[value];
}

function formatFree(value, row, index){
    if (!value || value == '') {
        return '';
    }
    if(value == 'Y'){
        return '否';
    }else{
        return '是';
    }

}
function dataType(value, row, index){
    if (value == 'lesson_series') {
        return '是';
    }
    return '否';
}

/*清空表单*/
function clearFrom(formId) {
    var formObj = $("#" + formId);
    if(formId && formObj){
        formObj.clearForm(true);
    }
}

